/*
 * Copyright 2002-2005 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.springframework.remoting.jsonrpc;

import java.net.MalformedURLException;

import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.remoting.support.RemoteInvocation;
import org.springframework.remoting.support.UrlBasedRemoteAccessor;

import org.jabsorb.serializer.impl.ArraySerializer;
import org.jabsorb.serializer.impl.BeanSerializer;
import org.jabsorb.serializer.impl.BooleanSerializer;
import org.jabsorb.serializer.impl.DateSerializer;
import org.jabsorb.serializer.impl.DictionarySerializer;
import org.jabsorb.JSONSerializer;
import org.jabsorb.serializer.impl.ListSerializer;
import org.jabsorb.serializer.impl.MapSerializer;
import org.jabsorb.serializer.impl.NumberSerializer;
import org.jabsorb.serializer.SerializerState;
import org.jabsorb.serializer.impl.SetSerializer;
import org.jabsorb.serializer.impl.StringSerializer;

public class JSONRPCClientInterceptor extends UrlBasedRemoteAccessor implements
		MethodInterceptor, InitializingBean {

	private JSONSerializer serializer;

	private static final Log logger = LogFactory
			.getLog(JSONRPCClientInterceptor.class);

	public void afterPropertiesSet()  {
		try {
			serializer.registerSerializer(new BeanSerializer());
			serializer.registerSerializer(new ArraySerializer());
			serializer.registerSerializer(new DictionarySerializer());
			serializer.registerSerializer(new MapSerializer());
			serializer.registerSerializer(new SetSerializer());
			serializer.registerSerializer(new ListSerializer());
			serializer.registerSerializer(new DateSerializer());
			serializer.registerSerializer(new StringSerializer());
			serializer.registerSerializer(new NumberSerializer());
			serializer.registerSerializer(new BooleanSerializer());
			serializer.registerSerializer(new PrimitiveSerializer());
			serializer.registerSerializer(new ClassSerializer());
		} catch (Exception e) {
			// TODO what to do with this exception?
			e.printStackTrace();
		}
	}

	public void setSerializer(JSONSerializer serializer) {
		this.serializer = serializer;
	}

	public Object invoke(MethodInvocation invocation) throws Throwable {
		logger.info("MethodInvocation:" + invocation.toString());
		RemoteInvocation ri = new RemoteInvocation(invocation);
		String json = serializer.toJSON(ri);
		logger.info(json);
		CommonsHttpInvokerRequestExecutor executor = new CommonsHttpInvokerRequestExecutor();
		String response;
		Object obj = null;
		response = executor.executeRequest(this.getServiceUrl(), json);
		logger.info(response);
		if (invocation.getMethod().getReturnType().isPrimitive()
				&& !invocation.getMethod().getReturnType().getName().equals(
						"void"))
			obj = serializer.unmarshall(new SerializerState(), invocation
					.getMethod().getReturnType(), response);
		else
			obj = serializer.fromJSON(response);

		return obj;
	}
}
